﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows.Threading;

namespace Triples {
    public class Timer : INotifyPropertyChanged {
        private const double UpdateIntervalSeconds = 0.001;
        private const string TwoDigitStringFormat = "00";

        public event PropertyChangedEventHandler PropertyChanged;
        public event EventHandler Finished;

        private Stopwatch Stopwatch;
        private DispatcherTimer UpdateTrigger;
        private bool IsFinished = false;

        //public string ElapsedTime {
        //    get { return ToString (); }
        //}
        public TimeSpan AllotedTime {
            get;
            private set;
        }

        public TimeSpan RemainingTime {
            get;
            private set;
        }


        public string Minutes {
            get { return RemainingTime.Minutes.ToString (TwoDigitStringFormat); }
        }

        public string Seconds {
            get { return RemainingTime.Seconds.ToString(TwoDigitStringFormat); }
        }

        public string Miliseconds {
            get { return ((RemainingTime.TotalSeconds * 10) % 100).ToString(TwoDigitStringFormat); }
        }

        public Timer(TimeSpan allotedTime) {
            AllotedTime = allotedTime;
            RemainingTime = new TimeSpan(0);
            Stopwatch = new Stopwatch();
            UpdateTrigger = new DispatcherTimer();
        }

        public void Start() {
            UpdateTrigger.Interval = TimeSpan.FromSeconds(UpdateIntervalSeconds);
            UpdateTrigger.Tick += OnUpdate;
            UpdateTrigger.Start();
            Stopwatch.Start();
        }


        public void Stop() {
            Stopwatch.Stop();
            UpdateTrigger.Stop();
            UpdateTrigger.Tick -= OnUpdate;
        }


        void OnUpdate(object sender, EventArgs e) {
            PropertyChangedEventHandler ev = PropertyChanged;

            TimeSpan elapsed = Stopwatch.Elapsed;

            if (AllotedTime < elapsed) Finish();
            else RemainingTime = AllotedTime - elapsed;
            if (null != ev) ev(this, new PropertyChangedEventArgs(string.Empty));
        }


        private void Finish() {

            if (!IsFinished) {
                EventHandler ev = Finished;

                IsFinished = true;
                Stop();
                RemainingTime = TimeSpan.FromSeconds(0);
                if (null != ev) ev(this, new EventArgs());
            }
        }
    }
}
